<template>
  <view class="container">
    <!-- 导航栏 -->

    <!-- 相关宠物信息 -->
    <view class="pet-info-card" v-if="pet">
      <view class="pet-avatar-container">
        <image :src="pet.photo || '/static/img/default-pet.png'" class="pet-avatar" mode="aspectFill"></image>
      </view>
      <view class="pet-details">
        <text class="pet-name">{{ pet.name }}</text>
        <text class="pet-breed">{{ pet.breed }}</text>
      </view>
    </view>

    <!-- 记录详情卡片 -->
    <view class="detail-card" v-if="record">
      <view class="record-header">
        <view class="record-icon">{{ getHealthIcon(record.type || record.recordType || record.content) }}</view>
        <view class="record-content">{{ record.content || record.title || (record.type || record.recordType) }}</view>
        
      </view>

      <view class="record-info">
        <view class="info-item">
          <text class="info-label">记录类型:</text>
          <text class="info-value">{{ record.type || record.recordType || record.content }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">记录日期:</text>
          <text class="info-value">{{ formatDate(record.recordDate) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">创建时间:</text>
          <text class="info-value">{{ formatDateTime(record.createTime) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">备注:</text>
          <text class="info-value">{{ record.remark }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮区域 -->
    <view class="bottom-action-section">
      <!-- 编辑和删除按钮 -->
      <view class="action-row">
        <button class="action-btn edit-btn" @click="editRecord">编辑</button>
        <button class="action-btn delete-btn" @click="deleteRecord">删除</button>
      </view>
      
      <!-- 状态操作按钮 -->
      <view class="action-row" v-if="record && isPendingStatus(record.status)">
        <button class="action-btn primary" @click="markAsCompleted">
        标记为已完成
      </button>
      </view>
      

    </view>
  </view>
</template>

<script>
import { getPetDetail } from '@/api/pet.js'
import { getHealthDetail } from '@/api/health.js'
import { checkAndRedirectToLogin, getUserId } from '@/utils/auth.js'
import { API_BASE } from '@/config/config.js'

export default {
  data() {
    return {
      recordId: null,
      record: null,
      pet: null
    }
  },
  onLoad(options) {
    const recordId = options.id
    if (recordId) {
      this.recordId = recordId
      this.loadRecordDetail(recordId)
    }
  },
  
  onShow() {
    // 页面每次显示时重新加载数据，确保标记完成后的数据更新
    if (this.recordId) {
      this.loadRecordDetail(this.recordId)
    }
  },
  methods: {
    async loadRecordDetail(recordId) {
      try {
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        // 检查是否为临时ID（以'temp_'开头的ID）
        if (typeof recordId === 'string' && recordId.startsWith('temp_')) {
          // 从本地存储获取临时健康记录数据
          const tempRecord = uni.getStorageSync(`temp_health_${recordId}`)
          if (tempRecord) {
            this.record = tempRecord
            
            // 加载相关宠物信息
            if (this.record.petId) {
              this.loadPetInfo(this.record.petId)
            }
            return
          } else {
            uni.showToast({
              title: '健康记录正在同步中，请稍后再试',
              icon: 'none'
            })
            return
          }
        }
        
        // 参考编辑页面的实现，使用直接的uni.request调用
        const response = await uni.request({
          url: `${API_BASE}/system/health/${recordId}`,
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })
        
        const [error, res] = response
        if (error || !res || res.statusCode !== 200) {
          console.error('http request failed:', error)
          throw new Error('加载记录失败')
        }
        
        const recordData = res.data.data || res.data
        this.record = recordData

        // 加载相关宠物信息
        if (this.record.petId) {
          this.loadPetInfo(this.record.petId)
        }
        
      } catch (error) {
        console.error('加载健康记录详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    
    async loadPetInfo(petId) {
      try {
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        // 参考编辑页面的实现，使用直接的uni.request调用
        const response = await uni.request({
          url: `${API_BASE}/system/pet/${petId}`,
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })
        
        const [error, res] = response
        if (error || !res || res.statusCode !== 200) {
          console.error('http request failed:', error)
          throw new Error('加载宠物信息失败')
        }
        
        const petData = res.data.data || res.data
        this.pet = petData
        
      } catch (error) {
        console.error('加载宠物信息失败:', error)
        uni.showToast({
          title: '加载宠物信息失败',
          icon: 'none'
        })
      }
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    isPendingStatus(status) {
      // 检查状态是否为待处理：支持数字0/1、字符串'0'/'1'、英文'pending'/'completed'/'overdue'
      return status === '0' || status === 0 || status === 'pending'
    },
    
    editRecord() {
      uni.navigateTo({
        url: `/pages/health/edit?id=${this.record.id}`
      })
    },
    
    deleteRecord() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个健康记录吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await uni.request({
                url: `${API_BASE}/system/health/${this.record.id}`,
                method: 'DELETE',
                header: {
                  'Authorization': 'Bearer ' + uni.getStorageSync('token'),
                  'Content-Type': 'application/json'
                }
              })
              
              const [error, res] = response
              
              if (res && res.statusCode === 200) {
                const responseData = res.data
                
                // 更灵活的成功判断：检查 code === 200 或者没有 code 字段但请求成功
                if (responseData && (responseData.code === 200 || !responseData.hasOwnProperty('code'))) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                setTimeout(() => {
                  // 获取页面栈，通知上一个页面刷新数据
                  const pages = getCurrentPages()
                  
                  if (pages.length > 1) {
                    const prevPage = pages[pages.length - 2]
                    // 如果上一个页面是日历详情页面，调用其刷新方法
                    if (prevPage.route === 'pages/calendar/detail') {
                      // 保存原始options以便在onShow中使用
                      if (prevPage.options && !prevPage.savedOptions) {
                        prevPage.savedOptions = {...prevPage.options}
                      }
                      // 设置刷新标志，让上一个页面在onShow时自动刷新
                      prevPage.needRefresh = true
                      // 强制更新上一个页面的数据
                      prevPage.$forceUpdate()
                    }
                  }
                  
                  const result = uni.navigateBack()
                  
                  // 如果navigateBack失败，尝试直接跳转到首页
                  setTimeout(() => {
                    const currentPages = getCurrentPages()
                    if (currentPages.length > 0 && currentPages[currentPages.length - 1].route === 'pages/health/detail') {
                      uni.switchTab({
                        url: '/pages/index/index'
                      })
                    }
                  }, 1000)
                }, 1500)
                } else {
                  uni.showToast({
                    title: responseData?.msg || '删除失败',
                    icon: 'none'
                  })
                }
              } else {
                uni.showToast({
                  title: error?.message || '删除失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              uni.showToast({
                title: error?.message || '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    markAsCompleted() {
      uni.showModal({
        title: '确认完成',
        content: '确定要将此记录标记为已完成吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const updateData = {
                ...this.record,
                status: '1', // 使用数字状态码
                reminderId: this.record.reminderId || '', // 确保包含提醒ID字段
                recordDate: this.record.recordDate || new Date().toISOString().split('T')[0] // 确保包含记录日期字段，如果没有则使用当前日期
              }
              
              const response = await uni.request({
                url: `${API_BASE}/system/health`,
                method: 'PUT',
                data: updateData,
                header: {
                  'Authorization': 'Bearer ' + uni.getStorageSync('token'),
                  'Content-Type': 'application/json'
                }
              })
              
              if (response.statusCode === 200) {
                const responseData = response.data
                
                if (responseData && responseData.code === 200) {
                  this.record.status = '1'
                  uni.showToast({
                    title: '标记成功',
                    icon: 'success'
                  })
                } else {
                  console.error('Business logic failed:', responseData?.msg)
                  uni.showToast({
                    title: responseData?.msg || '操作失败',
                    icon: 'none'
                  })
                }
              } else {
                console.error('HTTP request failed, status code:', response.statusCode)
                uni.showToast({
                  title: `操作失败 (${response.statusCode})`,
                  icon: 'none'
                })
              }
            } catch (error) {
              console.error('Mark as completed failed:', error)
              uni.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    

    getHealthIcon(type) {
      const icons = {
        '疫苗': '💉',
        '驱虫': '🦠',
        '体检': '🏥',
        '体重': '⚖️'
      }
      return icons[type] || '📋'
    },
    
    getStatusClass(status) {
      // 统一处理状态样式类：支持数字0/1、字符串'0'/'1'、英文'pending'/'completed'/'overdue'
      if (status === '0' || status === 0 || status === 'pending') {
        return 'status-pending'
      } else if (status === '1' || status === 1 || status === 'completed') {
        return 'status-completed'
      } else if (status === 'overdue') {
        return 'status-overdue'
      }
      return 'status-pending'
    },
    
    getStatusText(status) {
      // 统一处理状态值：支持数字0/1、字符串'0'/'1'、英文'pending'/'completed'/'overdue'
      if (status === '0' || status === 0 || status === 'pending') {
        return '待处理'
      } else if (status === '1' || status === 1 || status === 'completed') {
        return '已完成'
      } else if (status === 'overdue') {
        return '已逾期'
      }
      return '待处理'
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
  padding-bottom: 200rpx; /* 为底部按钮留出空间 */
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
}

.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.nav-actions {
  display: flex;
  gap: 10rpx;
}

.edit-btn, .delete-btn {
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

.edit-btn {
  background: #007AFF;
  color: #fff;
}

.delete-btn {
  background: #b7b4b4;
  color: #fff;
}

.detail-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.08);
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.record-icon {
  font-size: 60rpx;
  margin-right: 20rpx;
}

.record-content {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  margin-left: 20rpx;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.record-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.record-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.status-pending {
  background: #FFF3CD;
  color: #856404;
}

.status-completed {
  background: #D4EDDA;
  color: #155724;
}

.status-overdue {
  background: #F8D7DA;
  color: #721C24;
}

.record-info {
  margin-bottom: 30rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.reminder-date {
  color: #FF9500;
}

.record-description, .record-remark {
  margin-bottom: 20rpx;
}

.description-title, .remark-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.description-content, .remark-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.pet-info-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
}

.pet-avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}

.pet-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.pet-details {
  text-align: center;
}

.pet-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  text-align: center;
}

.pet-breed {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  display: block;
}

/* 底部操作按钮区域 */
.bottom-action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  width: calc(100% - 20rpx);
  background: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.08);
  z-index: 10;
  box-sizing: border-box;
}

.action-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.action-row:last-child {
  margin-bottom: 0;
}

.action-btn {
  flex: 1;
  padding: 20rpx;
  border: none;
  border-radius: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.edit-btn {
  background: #007AFF;
  color: #fff;
}

.delete-btn {
  background: #fff;
  color: #999;
  border: 1px solid #999;
  margin-right: 1px;
}

.primary {
  background: #007AFF;
  color: #fff;
}

.secondary {
  background: #f0f0f0;
  color: #333;
}
</style>